package com.hotel.order.controller;

import com.hotel.common.utils.DBTools;
import com.hotel.common.utils.Result;
import com.hotel.order.mq.OrderCreatedPublisher;
import org.springframework.beans.factory.annotation.Qualifier;
import java.util.concurrent.Executor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order/orders")
public class OrderController {

    @Autowired
    private OrderCreatedPublisher publisher;

    @Autowired
    @Qualifier("orderExecutor")
    private Executor orderExecutor;

    @GetMapping
    public Result<List<Map<String, String>>> list(@RequestParam(name = "userId", required = false) Long userId) {
        String base = "SELECT id, user_id AS userId, hotel_id AS hotelId, room_id AS roomId, status, checkin_date AS checkinDate, checkout_date AS checkoutDate, amount, created_at AS createdAt FROM orders";
        List<Map<String, String>> data = userId == null
                ? DBTools.query(base + " ORDER BY id DESC")
                : DBTools.query(base + " WHERE user_id=? ORDER BY id DESC", userId);
        return Result.success(data);
    }

    @PostMapping
    public synchronized Result<Long> create(@RequestBody Map<String, Object> body) {
        Long userId = body.get("userId") == null ? null : Long.parseLong(body.get("userId").toString());
        Long hotelId = Long.parseLong(body.get("hotelId").toString());
        Long roomId = Long.parseLong(body.get("roomId").toString());
        String checkinDate = (String) body.get("checkinDate");
        String checkoutDate = (String) body.get("checkoutDate");
        // 动态价格：入住日期命中季节价则取季节价，否则取基础价
        String season = DBTools.querySingle("SELECT price FROM room_price_season WHERE room_id=" + roomId + " AND '" + checkinDate + "' BETWEEN start_date AND end_date ORDER BY id DESC LIMIT 1");
        Double amount;
        if (season != null && season.length() > 0) {
            amount = Double.parseDouble(season);
        } else {
            String base = DBTools.querySingle("SELECT price FROM room WHERE id=" + roomId);
            amount = Double.parseDouble(base);
        }
        // 扣减库存（高并发下使用行级锁）
        int affected = DBTools.update("UPDATE room SET inventory = inventory - 1 WHERE id=? AND inventory > 0", roomId);
        if (affected == 0) {
            return Result.fail("房间库存不足");
        }
        // 创建订单
        String sql = "INSERT INTO orders(user_id,hotel_id,room_id,status,checkin_date,checkout_date,amount) VALUES(?,?,?,?,?,?,?)";
        DBTools.update(sql, userId, hotelId, roomId, "CREATED", checkinDate, checkoutDate, amount);
        String id = DBTools.querySingle("SELECT LAST_INSERT_ID() AS id");
        Long orderId = Long.valueOf(id);
        // 异步任务：日志、风控检查、异步消息投递（失败重试可在MQ配置层实现重试机制）
        orderExecutor.execute(() -> {
            try {
                DBTools.update("INSERT INTO orders_log(order_id, content) VALUES(?, ?)", orderId, "created");
            } catch (Exception ignored) {}
            publisher.publishOrderCreated(orderId);
        });
        return Result.success(orderId);
    }

    @DeleteMapping("/{id}")
    public Result<Void> cancel(@PathVariable("id") Long id) {
        String sql = "UPDATE orders SET status='CANCELLED' WHERE id=?";
        DBTools.update(sql, id);
        return Result.success();
    }
}
